package com.zxy.leetcode._00000_00099._00060_00069;

/**
 * https://leetcode-cn.com/problems/add-binary/
 *
 * 二进制求和
 * 给你两个二进制字符串，返回它们的和（用二进制表示）。
 * 输入为 非空 字符串且只包含数字 1 和 0。
 *
 * 标签：数字、字符串
 */
public class Test00067 {

    public static void main(String[] args) {
        Test00067 test = new Test00067();
        System.out.println(test.addBinary("0","0"));
        System.out.println(test.addBinary("0","1"));
        System.out.println(test.addBinary("11","1"));
        System.out.println(test.addBinary("1010","1011"));
    }

    public String addBinary(String a, String b) {
        if ("0".equals(a))  return b;
        if ("0".equals(b))  return a;

        StringBuilder sb = new StringBuilder(Math.max(a.length(), b.length()) + 1);

        String maxStr, minStr;
        if (a.length() > b.length()) {
            maxStr = a;
            minStr = b;
        }else {
            maxStr = b;
            minStr = a;
        }

        int minLen = minStr.length();
        int maxLen = maxStr.length();
        boolean flag = false;

        for (int i=1; i<=minLen; i++) {
            char c1 = maxStr.charAt(maxLen-i);
            char c2 = minStr.charAt(minLen-i);
            if (flag) {
                if (c1 == '1') {
                    if (c2 == '1') {
                        sb.append("1");
                        flag = true;
                    }else {
                        sb.append("0");
                        flag = true;
                    }
                }else {
                    if (c2 == '1') {
                        sb.append("0");
                        flag = true;
                    }else {
                        sb.append("1");
                        flag = false;
                    }
                }
            }else {

                if (c1 == '1') {
                    if (c2 == '1') {
                        sb.append("0");
                        flag = true;
                    }else {
                        sb.append("1");
                        flag = false;
                    }
                }else {
                    if (c2 == '1') {
                        sb.append("1");
                        flag = false;
                    }else {
                        sb.append("0");
                        flag = false;
                    }
                }
            }
        }

        for (int i=minLen+1; i<=maxLen; i++) {
            char c1 = maxStr.charAt(maxLen-i);
            if (flag) {
                if (c1 == '1') {
                    sb.append("0");
                    flag = true;
                }else {
                    sb.append("1");
                    flag = false;
                }
            }else {
                sb.append(c1);
                flag = false;
            }
        }
        if (flag) {
            sb.append("1");
        }

        return sb.reverse().toString();
    }
}
